﻿using Shoy.Wcf;
using Shoy.Wcf.Contract;
using System;
using System.Collections.Generic;
using System.DirectoryServices;
using System.Net;
using System.ServiceModel;
using System.Threading;
using System.Web;

[assembly: WebActivatorEx.PostApplicationStartMethod(typeof(HelloService.Startup), "Start")]
[assembly: WebActivatorEx.ApplicationShutdownMethod(typeof(HelloService.Startup), "ShutDown")]
namespace HelloService
{
    public class Startup
    {
        private static List<ServiceHost> _hosts;

        static Startup()
        {
            _hosts = new List<ServiceHost>();
        }
        public static void Start()
        {
            var host = WcfHelper.Instance.OpenService(typeof(IHelloContract), typeof(HelloContract),
                msg =>
                {
                    var cache = Consts.GetCache();
                    var list = cache.Get<List<string>>(Consts.MessageCacheKey) ?? new List<string>();
                    list.Add(msg);
                    cache.Set(Consts.MessageCacheKey, list);
                });
            _hosts.Add(host);
        }

        private string GetUrl()
        {
            var path = System.Web.Hosting.HostingEnvironment.ApplicationID; //值类似于:/LM/W3SVC/3/ROOT
            var url = string.Empty;
            try
            {
                //如果HttpContext可以访问就直接返回通过HttpContext获取的结果
                return HttpContext.Current.Request.Url.ToString();
            }
            catch (Exception)
            {
            }
            // 将Path转换成IIS路径
            path = path.Replace("/LM", "").Replace("/ROOT", "");
            var entPath = $"IIS://localhost{path}";
            var entry = new DirectoryEntry(entPath);
            if (!entry.Properties.Contains("ServerBindings")) return url;
            var bingdings = entry.Properties["ServerBindings"].Value.ToString(); //得到的结果类似于10.188.188.13:8082: 
            //去掉结尾的 : 号
            if (bingdings.EndsWith(":"))
            {
                bingdings = bingdings.Substring(0, bingdings.Length - 1);
            }
            url = "http://" + bingdings;
            return url;
        }

        public static void ShutDown()
        {
            foreach (var host in _hosts)
            {
                host.Close();
            }
            _hosts = null;
            // 在应用程序关闭时运行的代码   
            //解决应用池回收问题   
            Thread.Sleep(2000);
            const string strUrl = "http://wcf.shay.com";
            var httpWebRequest = (HttpWebRequest)WebRequest.Create(strUrl);
            var httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            httpWebResponse.GetResponseStream(); //得到回写的字节流  
        }
    }
}